package main

import (
	"context"
	"fmt"
	"golang.org/x/sync/errgroup"
	"log"
	"net/http"
	"os"
	"os/signal"
)
func httpserver(ctx context.Context,sr *http.Server)error{
	http.HandleFunc("/hello", func(writer http.ResponseWriter, request *http.Request) {
		writer.Write([]byte("hello world"))
	})
	if err := sr.ListenAndServe(); err!=nil{
		return err
	}
	select {
	case <-ctx.Done():
		fmt.Println("http.server stop")
		sr.Shutdown(ctx)
		return ctx.Err()
	}
	return nil
}
func main()  {
	ctx,cancel:=context.WithCancel(context.Background())
	group,errctx:=errgroup.WithContext(ctx)
	srv := &http.Server{Addr: ":9090"}
	group.Go(func() error {
		return httpserver(errctx,srv)
	})
	chancel:=make(chan os.Signal,1)
	signal.Notify(chancel)
	group.Go(func() error {
		select {
		case <-chancel:
			log.Println("优雅关闭http服务")
			cancel()
		case <-errctx.Done():
			return errctx.Err()
		}
		return nil
	})
	if err := group.Wait(); err != nil {
		fmt.Println("group error: ", err)
	}
	fmt.Println("任务完成")
}
